package com.health.trans.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.health.trans.annotation.BatchJob;
import com.health.trans.common.entity.ApiResponse;
import com.health.trans.job.AbstractJob;
import com.health.trans.pojo.TableRes;
import com.health.trans.pojo.TransParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author nqlz
 */
@Service
@Slf4j
public class BatchTransService {

    public static TaskExecutor myTaskExecutor;
    public static Map<String, AbstractJob> mysqlToSthMap;

    public BatchTransService(TaskExecutor myTaskExecutor,  ApplicationContext applicationContext) {
        BatchTransService.myTaskExecutor = myTaskExecutor;
        Map<String, AbstractJob> objectMap = applicationContext.getBeansOfType(AbstractJob.class);
        Map<String, AbstractJob> finalMap = ObjectUtil.clone(objectMap);
        objectMap.forEach((k,v)-> {
            if (finalMap.containsKey(k)){
                return;
            }
            MapUtil.renameKey(finalMap, k, v.getClass().getAnnotation(BatchJob.class).transTypeName());
        });
        BatchTransService.mysqlToSthMap = finalMap;
    }

    /**
     * MySQL发送其他地方
     *
     * @param param 参数
     * @return {@link ApiResponse}
     */
    public static <T> ApiResponse<List<TableRes>> mysqlToSth(TransParam param) {
        ApiResponse<List<TableRes>> error = getListApiResponse(param);
        if (error != null) {
            return error;
        }
        return ApiResponse.ok(AbstractJob.execute(param));
    }

    private static ApiResponse<List<TableRes>> getListApiResponse(TransParam param) {
        //校验param
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(param);
        List<String> error = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(error)) {
            return ApiResponse.error(error.toString());
        }
        return null;
    }


}
